import {
  valueTypeTransform
} from 'src/util'
// 表单模型解析函数，根据formrule解析，返回一个表单对象数据
let modleTranslate = {
  // 普通输入框组
  inputgroup (model) {
    let startId = model.id[0]
    let endId = model.id[1]
    return {
      [startId]: model.defaultVal[0] || '',
      [endId]: model.defaultVal[1] || ''
    }
  },
  // 日期选择组
  datePickerGroup (model) {
    let startId = model.id[0]
    let endId = model.id[1]
    return {
      [startId]: model.defaultVal[0] || '',
      [endId]: model.defaultVal[1] || ''
    }
  },
  // 下拉选择框组
  select (model) {
    let id = model.id
    if (model.multiple) {
      return {
        [id]: [...model.defaultVal]
      }
    } else {
      return {
        [id]: model.defaultVal
      }
    }
  },
  // 默认选择
  default (model) {
    let id = model.id
    return {
      [id]: model.defaultVal || ''
    }
  }
}
// quertyParam 转表单描述 的一些规则
let queryTranslate = {
  datePickerGroup (val) {
    return new Date(parseInt(val))
  },
  default (val) {
    return val
  }
}
// 表单描述规则 ，转换成表单对象
export const formTranslate = (modelArr) => {
  let formParams = {}
  modelArr.forEach((item) => {
    let {formtype} = item
    let modelObj = {}
    if (modleTranslate[formtype]) {
      modelObj = modleTranslate[formtype](item)
    } else {
      modelObj = modleTranslate['default'](item)
    }
    formParams = Object.assign(formParams, modelObj)
  })
  return formParams
}
// 根据url query给表单描述规则赋默认值
export const setDefaultFromQuery = (formRule, queryParam) => {
  formRule = formRule || []
  queryParam = queryParam || {}
  let len = formRule.length
  for (let key in queryParam) {
    for (let i = 0; i < len; i++) {
      let idIndex = formRule[i].id.indexOf(key)
      if (idIndex > -1) {
        let ruleArr = Object.keys(queryTranslate)
        let formtype = ruleArr.indexOf(formRule[i].formtype) > -1 ? formRule[i].formtype : 'default'
        // 强校验表单值的类型，
        // 支持4种值类型强制转换  String Array
        let type = formRule[i].type
        if (!type) {
          throw new Error('表单值类型未知')
        }
        if (typeof formRule[i].id === 'string') {
          let defaultVal = queryTranslate[formtype](queryParam[key])
          formRule[i].defaultVal = valueTypeTransform(defaultVal, type)
        } else {
          let defaultVal = queryTranslate[formtype](queryParam[key])
          formRule[i].defaultVal[idIndex] = valueTypeTransform(defaultVal, type)
        }
        continue
      }
    }
  }
  return formRule
}
